/**
 * TDS PEC 4
 * Grupo 3H2M
 *
 * El paquete <code>edu.uoc.tds.pec4.mantenimiento</code> agrupa todas las
 * interfaces, clases y elementos de la GUI para la gestión del subsistema 
 * de Mantenimiento
 */
package edu.uoc.tds.pec4.mantenimiento;

import edu.uoc.tds.pec4.rmi.GestorMantenimientoInterface;
import edu.uoc.tds.pec4.beans.AuditoriaDTO;
import edu.uoc.tds.pec4.beans.CiudadDTO;
import edu.uoc.tds.pec4.beans.UsuarioDTO;
import edu.uoc.tds.pec4.common.util.Constantes;
import edu.uoc.tds.pec4.common.util.TDSLanguageUtils;
import edu.uoc.tds.pec4.common.util.UtilidadesGUI;
import edu.uoc.tds.pec4.common.validation.ValidarGUI;
import edu.uoc.tds.pec4.server.bbdd.exceptions.GestorMantenimientoException;
import java.awt.Frame;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.net.MalformedURLException;
import java.rmi.Naming;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import javax.swing.JButton;
import javax.swing.JOptionPane;

/**
 * La clase <code>DialogAltaUsuario</code> representa la interfaz de
 * usuario para el alta de un usuario.<br />
 *
 * Interficie de usuario para el alta de usuarios.
 *
 * @author	Luis Rivas Mariño
 * @version	10/12/2011
 * @see		edu.uoc.tds.pec4.common.GestorMantenimientoInterface
 */
public class DialogAltaUsuario extends javax.swing.JDialog {

    private javax.swing.JTextField apellidos;
    private javax.swing.JButton btnBuscar;
    private javax.swing.JButton btnCancelar;
    private javax.swing.JButton btnConfirmar;
    private javax.swing.JTextField cc;
    private javax.swing.JTextField ciudad;
    private javax.swing.JTextField codPostal;
    private javax.swing.JTextField direccion;
    private javax.swing.JTextField email;
    private javax.swing.JTextField fax;
    private javax.swing.JTextField idUsuario;
    private javax.swing.JCheckBox inactivo;
    private javax.swing.JLabel lblApellidos;
    private javax.swing.JLabel lblCc;
    private javax.swing.JLabel lblCiudad;
    private javax.swing.JLabel lblCodPostal;
    private javax.swing.JLabel lblDireccion;
    private javax.swing.JLabel lblEmail;
    private javax.swing.JLabel lblFax;
    private javax.swing.JLabel lblIdUsuario;
    private javax.swing.JLabel lblMovil;
    private javax.swing.JLabel lblNif;
    private javax.swing.JLabel lblNombre;
    private javax.swing.JLabel lblPsw;
    private javax.swing.JLabel lblTelefono;
    private javax.swing.JTextField movil;
    private javax.swing.JTextField nif;
    private javax.swing.JTextField nomCiudad;
    private javax.swing.JTextField nombre;
    private javax.swing.JPanel panelBotones;
    private javax.swing.JPanel panelCC;
    private javax.swing.JPanel panelContacto;
    private javax.swing.JPanel panelDatos;
    private javax.swing.JPanel panelDireccion;
    private javax.swing.JPanel panelRoles;
    private javax.swing.JTextField psw;
    private javax.swing.JCheckBox rolAdmin;
    private javax.swing.JCheckBox rolCliente;
    private javax.swing.JCheckBox rolTecn;
    private javax.swing.JTextField telefono;
    /** clientConnected Indica si el cliente está conectado al servidor */
    private boolean clientConnected = false;
    /** objRemoto es el objeto empleado como interfaz en la comunicación RMI */
    private GestorMantenimientoInterface objRemotoMantenimiento = null;
    /** usLogeado representa al usuario que está autentificado */
    private UsuarioDTO usLogeado;
    // Identificador del usuario conectado
    private String idConectado;
    // Validaciones
    boolean error = false;

    /** Crea un nuevo formulario DialogAltaUsuario */
    public DialogAltaUsuario(java.awt.Frame parent, boolean modal, UsuarioDTO usLogeado) {
        super(parent, TDSLanguageUtils.getMessage("mantenimiento.usuario.alta.titulo"), modal);

        conectarCliente();

        inicializaComponentes();

        // Obtenemos el usuario conectado
        this.usLogeado = usLogeado;
        idConectado = usLogeado.getIdUsuario();

        //Centramos la ventana en la pantalla
        UtilidadesGUI.centrarVentana(this);
    }

    /** Este método es llamado desde el constructor para 
     *  inicializar el formulario.
     */
    private void inicializaComponentes() {

        panelDireccion = new javax.swing.JPanel();
        lblDireccion = new javax.swing.JLabel();
        direccion = new javax.swing.JTextField();
        lblCiudad = new javax.swing.JLabel();
        lblCodPostal = new javax.swing.JLabel();
        codPostal = new javax.swing.JTextField();
        ciudad = new javax.swing.JTextField();
        btnBuscar = new javax.swing.JButton();
        nomCiudad = new javax.swing.JTextField();
        panelBotones = new javax.swing.JPanel();
        btnConfirmar = new javax.swing.JButton();
        btnCancelar = new javax.swing.JButton();
        panelDatos = new javax.swing.JPanel();
        lblNombre = new javax.swing.JLabel();
        nombre = new javax.swing.JTextField();
        lblApellidos = new javax.swing.JLabel();
        apellidos = new javax.swing.JTextField();
        lblNif = new javax.swing.JLabel();
        nif = new javax.swing.JTextField();
        lblIdUsuario = new javax.swing.JLabel();
        idUsuario = new javax.swing.JTextField();
        lblPsw = new javax.swing.JLabel();
        inactivo = new javax.swing.JCheckBox();
        psw = new javax.swing.JTextField();
        panelCC = new javax.swing.JPanel();
        lblCc = new javax.swing.JLabel();
        cc = new javax.swing.JTextField();
        panelContacto = new javax.swing.JPanel();
        lblEmail = new javax.swing.JLabel();
        email = new javax.swing.JTextField();
        lblTelefono = new javax.swing.JLabel();
        telefono = new javax.swing.JTextField();
        movil = new javax.swing.JTextField();
        lblFax = new javax.swing.JLabel();
        fax = new javax.swing.JTextField();
        lblMovil = new javax.swing.JLabel();
        panelRoles = new javax.swing.JPanel();
        rolAdmin = new javax.swing.JCheckBox();
        rolTecn = new javax.swing.JCheckBox();
        rolCliente = new javax.swing.JCheckBox();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        panelDireccion.setBorder(javax.swing.BorderFactory.createTitledBorder(null, TDSLanguageUtils.getMessage("mantenimiento.gui.panel.direccion"), javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font(Constantes.TAHOMA, 1, 11)));


        lblDireccion.setText(TDSLanguageUtils.getMessage("mantenimiento.gui.etiqueta.direccion"));

        direccion.setHorizontalAlignment(javax.swing.JTextField.LEFT);

        lblCiudad.setText(TDSLanguageUtils.getMessage("mantenimiento.gui.etiqueta.localidad"));

        lblCodPostal.setText(TDSLanguageUtils.getMessage("mantenimiento.gui.etiqueta.codpostal"));

        codPostal.setHorizontalAlignment(javax.swing.JTextField.CENTER);
        
        

        ciudad.setEditable(false);
        ciudad.setHorizontalAlignment(javax.swing.JTextField.CENTER);

        btnBuscar.setText(TDSLanguageUtils.getMessage("mantenimiento.gui.boton.buscar"));
        btnBuscar.addActionListener(new java.awt.event.ActionListener() {

            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnBuscarActionPerformed(evt);
            }
        });

        nomCiudad.setEditable(false);
        nomCiudad.setHorizontalAlignment(javax.swing.JTextField.LEFT);

        javax.swing.GroupLayout panelDireccionLayout = new javax.swing.GroupLayout(panelDireccion);
        panelDireccion.setLayout(panelDireccionLayout);
        panelDireccionLayout.setHorizontalGroup(
                panelDireccionLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGroup(panelDireccionLayout.createSequentialGroup().addContainerGap().addGroup(panelDireccionLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING).addGroup(javax.swing.GroupLayout.Alignment.LEADING, panelDireccionLayout.createSequentialGroup().addComponent(lblDireccion).addGap(19, 19, 19).addComponent(direccion, javax.swing.GroupLayout.DEFAULT_SIZE, 412, Short.MAX_VALUE)).addGroup(javax.swing.GroupLayout.Alignment.LEADING, panelDireccionLayout.createSequentialGroup().addComponent(lblCiudad).addGap(18, 18, 18).addComponent(ciudad, javax.swing.GroupLayout.PREFERRED_SIZE, 38, javax.swing.GroupLayout.PREFERRED_SIZE).addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED).addComponent(nomCiudad, javax.swing.GroupLayout.PREFERRED_SIZE, 133, javax.swing.GroupLayout.PREFERRED_SIZE).addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED).addComponent(btnBuscar).addGap(18, 18, 18).addComponent(lblCodPostal).addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED).addComponent(codPostal, javax.swing.GroupLayout.PREFERRED_SIZE, 76, javax.swing.GroupLayout.PREFERRED_SIZE))).addContainerGap()));
        panelDireccionLayout.setVerticalGroup(
                panelDireccionLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGroup(panelDireccionLayout.createSequentialGroup().addGroup(panelDireccionLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE).addComponent(direccion, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE).addComponent(lblDireccion)).addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED).addGroup(panelDireccionLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE).addComponent(lblCiudad).addComponent(ciudad, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE).addComponent(codPostal, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE).addComponent(lblCodPostal).addComponent(btnBuscar).addComponent(nomCiudad, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)).addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)));

        btnConfirmar.setText(TDSLanguageUtils.getMessage("mantenimiento.gui.boton.aceptar"));
        btnConfirmar.addActionListener(new java.awt.event.ActionListener() {

            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnConfirmarActionPerformed(evt);
            }
        });

        btnCancelar.setText(TDSLanguageUtils.getMessage("mantenimiento.gui.boton.cancelar"));
        btnCancelar.addActionListener(new java.awt.event.ActionListener() {

            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCancelarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout panelBotonesLayout = new javax.swing.GroupLayout(panelBotones);
        panelBotones.setLayout(panelBotonesLayout);
        panelBotonesLayout.setHorizontalGroup(
                panelBotonesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGroup(javax.swing.GroupLayout.Alignment.TRAILING, panelBotonesLayout.createSequentialGroup().addContainerGap(171, Short.MAX_VALUE).addComponent(btnConfirmar).addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED).addComponent(btnCancelar).addGap(191, 191, 191)));
        panelBotonesLayout.setVerticalGroup(
                panelBotonesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGroup(javax.swing.GroupLayout.Alignment.TRAILING, panelBotonesLayout.createSequentialGroup().addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE).addGroup(panelBotonesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE).addComponent(btnConfirmar).addComponent(btnCancelar)).addContainerGap()));

        panelDatos.setBorder(javax.swing.BorderFactory.createTitledBorder(null, TDSLanguageUtils.getMessage("mantenimiento.gui.panel.datosgenerales"), javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font(Constantes.TAHOMA, 1, 11)));

        lblNombre.setText(TDSLanguageUtils.getMessage("mantenimiento.gui.etiqueta.nombre"));

        nombre.setHorizontalAlignment(javax.swing.JTextField.LEFT);

        lblApellidos.setText(TDSLanguageUtils.getMessage("mantenimiento.gui.etiqueta.apellidos"));

        apellidos.setHorizontalAlignment(javax.swing.JTextField.LEFT);

        lblNif.setText(TDSLanguageUtils.getMessage("mantenimiento.gui.etiqueta.nif"));

        nif.setHorizontalAlignment(javax.swing.JTextField.RIGHT);

        lblIdUsuario.setText(TDSLanguageUtils.getMessage("mantenimiento.gui.etiqueta.idusuario"));

        idUsuario.setHorizontalAlignment(javax.swing.JTextField.CENTER);

        lblPsw.setText(TDSLanguageUtils.getMessage("mantenimiento.gui.etiqueta.psw"));

        inactivo.setSelected(true);
        inactivo.setText(TDSLanguageUtils.getMessage("mantenimiento.gui.etiqueta.inactivo"));
        inactivo.setEnabled(false);

        psw.setHorizontalAlignment(javax.swing.JTextField.LEFT);

        javax.swing.GroupLayout panelDatosLayout = new javax.swing.GroupLayout(panelDatos);
        panelDatos.setLayout(panelDatosLayout);
        panelDatosLayout.setHorizontalGroup(
                panelDatosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGroup(panelDatosLayout.createSequentialGroup().addContainerGap().addGroup(panelDatosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addComponent(lblIdUsuario).addComponent(lblNombre)).addGap(14, 14, 14).addGroup(panelDatosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false).addComponent(nombre).addComponent(idUsuario, javax.swing.GroupLayout.DEFAULT_SIZE, 128, Short.MAX_VALUE)).addGap(18, 18, 18).addGroup(panelDatosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGroup(panelDatosLayout.createSequentialGroup().addComponent(lblPsw).addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED).addComponent(psw, javax.swing.GroupLayout.PREFERRED_SIZE, 130, javax.swing.GroupLayout.PREFERRED_SIZE)).addGroup(panelDatosLayout.createSequentialGroup().addGroup(panelDatosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addComponent(lblApellidos).addComponent(lblNif)).addGroup(panelDatosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGroup(panelDatosLayout.createSequentialGroup().addGap(24, 24, 24).addComponent(nif, javax.swing.GroupLayout.PREFERRED_SIZE, 106, javax.swing.GroupLayout.PREFERRED_SIZE).addGap(18, 18, 18).addComponent(inactivo)).addGroup(javax.swing.GroupLayout.Alignment.TRAILING, panelDatosLayout.createSequentialGroup().addGap(24, 24, 24).addComponent(apellidos, javax.swing.GroupLayout.PREFERRED_SIZE, 189, javax.swing.GroupLayout.PREFERRED_SIZE))))).addContainerGap()));
        panelDatosLayout.setVerticalGroup(
                panelDatosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGroup(panelDatosLayout.createSequentialGroup().addGap(1, 1, 1).addGroup(panelDatosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE).addComponent(lblIdUsuario).addComponent(idUsuario, javax.swing.GroupLayout.PREFERRED_SIZE, 19, javax.swing.GroupLayout.PREFERRED_SIZE).addComponent(lblNif).addComponent(nif, javax.swing.GroupLayout.PREFERRED_SIZE, 19, javax.swing.GroupLayout.PREFERRED_SIZE).addComponent(inactivo)).addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED).addGroup(panelDatosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE).addComponent(lblNombre).addComponent(nombre, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE).addComponent(lblApellidos).addComponent(apellidos, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)).addGap(18, 18, 18).addGroup(panelDatosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE).addComponent(lblPsw).addComponent(psw, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)).addContainerGap()));

        panelCC.setBorder(javax.swing.BorderFactory.createTitledBorder(null, TDSLanguageUtils.getMessage("mantenimiento.gui.panel.formapago"), javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font(Constantes.TAHOMA, 1, 11)));

        lblCc.setText(TDSLanguageUtils.getMessage("mantenimiento.gui.etiqueta.cc"));

        cc.setHorizontalAlignment(javax.swing.JTextField.CENTER);

        cc.addFocusListener(new java.awt.event.FocusAdapter() {

            public void focusLost(java.awt.event.FocusEvent evt) {
                ccFocusLost(evt);
            }
        });

        javax.swing.GroupLayout panelCCLayout = new javax.swing.GroupLayout(panelCC);
        panelCC.setLayout(panelCCLayout);
        panelCCLayout.setHorizontalGroup(
                panelCCLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGroup(panelCCLayout.createSequentialGroup().addContainerGap().addComponent(lblCc).addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED).addComponent(cc, javax.swing.GroupLayout.PREFERRED_SIZE, 369, javax.swing.GroupLayout.PREFERRED_SIZE).addContainerGap(24, Short.MAX_VALUE)));
        panelCCLayout.setVerticalGroup(
                panelCCLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGroup(panelCCLayout.createSequentialGroup().addGroup(panelCCLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE).addComponent(cc, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE).addComponent(lblCc)).addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)));

        panelContacto.setBorder(javax.swing.BorderFactory.createTitledBorder(null, TDSLanguageUtils.getMessage("mantenimiento.gui.panel.datoscontacto"), javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font(Constantes.TAHOMA, 1, 11)));

        lblEmail.setText(TDSLanguageUtils.getMessage("mantenimiento.gui.etiqueta.email"));

        email.setHorizontalAlignment(javax.swing.JTextField.LEFT);

        lblTelefono.setText(TDSLanguageUtils.getMessage("mantenimiento.gui.etiqueta.telefono"));

        telefono.setHorizontalAlignment(javax.swing.JTextField.CENTER);

        movil.setHorizontalAlignment(javax.swing.JTextField.CENTER);

        lblFax.setText(TDSLanguageUtils.getMessage("mantenimiento.gui.etiqueta.fax"));

        fax.setHorizontalAlignment(javax.swing.JTextField.CENTER);

        lblMovil.setText(TDSLanguageUtils.getMessage("mantenimiento.gui.etiqueta.movil"));

        javax.swing.GroupLayout panelContactoLayout = new javax.swing.GroupLayout(panelContacto);
        panelContacto.setLayout(panelContactoLayout);
        panelContactoLayout.setHorizontalGroup(
                panelContactoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGroup(panelContactoLayout.createSequentialGroup().addContainerGap().addGroup(panelContactoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addComponent(lblEmail).addGroup(panelContactoLayout.createSequentialGroup().addComponent(lblTelefono).addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED).addComponent(telefono, javax.swing.GroupLayout.PREFERRED_SIZE, 98, javax.swing.GroupLayout.PREFERRED_SIZE))).addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED).addGroup(panelContactoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGroup(panelContactoLayout.createSequentialGroup().addComponent(lblMovil).addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED).addComponent(movil, javax.swing.GroupLayout.PREFERRED_SIZE, 86, javax.swing.GroupLayout.PREFERRED_SIZE).addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 85, Short.MAX_VALUE).addComponent(lblFax).addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED).addComponent(fax, javax.swing.GroupLayout.PREFERRED_SIZE, 82, javax.swing.GroupLayout.PREFERRED_SIZE)).addComponent(email, javax.swing.GroupLayout.DEFAULT_SIZE, 311, Short.MAX_VALUE)).addGap(23, 23, 23)));
        panelContactoLayout.setVerticalGroup(
                panelContactoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGroup(panelContactoLayout.createSequentialGroup().addContainerGap().addGroup(panelContactoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING).addGroup(panelContactoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE).addComponent(lblTelefono).addComponent(telefono, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)).addGroup(panelContactoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE).addComponent(movil, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE).addComponent(lblMovil).addComponent(fax, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE).addComponent(lblFax))).addGroup(panelContactoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGroup(panelContactoLayout.createSequentialGroup().addGap(9, 9, 9).addComponent(lblEmail)).addGroup(panelContactoLayout.createSequentialGroup().addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED).addComponent(email, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))).addContainerGap()));

        panelRoles.setBorder(javax.swing.BorderFactory.createTitledBorder(null, TDSLanguageUtils.getMessage("mantenimiento.gui.panel.roles"), javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font(Constantes.TAHOMA, 1, 11)));

        rolAdmin.setText(TDSLanguageUtils.getMessage("mantenimiento.gui.etiqueta.administrador"));
        rolAdmin.addItemListener(new java.awt.event.ItemListener() {

            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                rolAdminItemStateChanged(evt);
            }
        });

        rolTecn.setText(TDSLanguageUtils.getMessage("mantenimiento.gui.etiqueta.tecnico"));
        rolTecn.addItemListener(new java.awt.event.ItemListener() {

            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                rolTecnItemStateChanged(evt);
            }
        });

        rolCliente.setText(TDSLanguageUtils.getMessage("mantenimiento.gui.etiqueta.cliente"));
        rolCliente.addItemListener(new java.awt.event.ItemListener() {

            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                rolClienteItemStateChanged(evt);
            }
        });

        javax.swing.GroupLayout panelRolesLayout = new javax.swing.GroupLayout(panelRoles);
        panelRoles.setLayout(panelRolesLayout);
        panelRolesLayout.setHorizontalGroup(
                panelRolesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGroup(panelRolesLayout.createSequentialGroup().addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE).addComponent(rolAdmin).addGap(33, 33, 33).addComponent(rolTecn).addGap(40, 40, 40).addComponent(rolCliente).addContainerGap()));
        panelRolesLayout.setVerticalGroup(
                panelRolesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGroup(panelRolesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE).addComponent(rolAdmin).addComponent(rolTecn).addComponent(rolCliente)));

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGroup(layout.createSequentialGroup().addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false).addComponent(panelDatos, javax.swing.GroupLayout.Alignment.LEADING, 0, 524, Short.MAX_VALUE).addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup().addGap(89, 89, 89).addComponent(panelRoles, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)).addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup().addContainerGap().addComponent(panelDireccion, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))).addGroup(layout.createSequentialGroup().addContainerGap().addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false).addComponent(panelCC, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE).addComponent(panelBotones, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE).addComponent(panelContacto, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))).addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)));
        layout.setVerticalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGroup(layout.createSequentialGroup().addComponent(panelDatos, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE).addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED).addComponent(panelRoles, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE).addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED).addComponent(panelDireccion, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE).addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED).addComponent(panelContacto, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE).addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED).addComponent(panelCC, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE).addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED).addComponent(panelBotones, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE).addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)));

        pack();
    }

    /**
     * Comprueba si el número de cuenta corriente tiene más de 20 caracteres
     * y, si tiene 20, valida la cuenta corriente introducida
     * @param evt 
     */
    private void ccFocusLost(java.awt.event.FocusEvent evt) {
        if (cc.getText().length() != 20) {
            JOptionPane.showMessageDialog(null, TDSLanguageUtils.getMessage("mantenimiento.gui.err.ccno20"));
            error = true;
        }
    }

        /**
     * Comprueba si el número de cuenta corriente tiene más de 20 caracteres
     * y, si tiene 20, valida la cuenta corriente introducida
     * @param evt 
     */
    private void codPostalFocusLost(java.awt.event.FocusEvent evt) {
        if (cc.getText().length() != 5) {
            JOptionPane.showMessageDialog(null, TDSLanguageUtils.getMessage("mantenimiento.gui.err.cpno5"));
            error = true;
        }
    }
    /**
     * Conectar con el servidor RMI
     * Permitela conexion con el servidor RMI
     */
    private void conectarCliente() {
        try {
            objRemotoMantenimiento = (GestorMantenimientoInterface) Naming.lookup("GestorMantenimiento");
            clientConnected = true;
        } catch (NotBoundException eNbe) {
            objRemotoMantenimiento = null;
            JOptionPane.showMessageDialog(null,
                    TDSLanguageUtils.getMessage("cliente.error.notbound") + "\n" + eNbe.getMessage(),
                    TDSLanguageUtils.getMessage("cliente.error"), JOptionPane.ERROR_MESSAGE);
        } catch (RemoteException eRe) {
            objRemotoMantenimiento = null;
            JOptionPane.showMessageDialog(null,
                    TDSLanguageUtils.getMessage("cliente.error.url") + "\n" + eRe.getMessage(),
                    TDSLanguageUtils.getMessage("cliente.error"), JOptionPane.ERROR_MESSAGE);
        } catch (MalformedURLException eMULRe) {
            objRemotoMantenimiento = null;
            JOptionPane.showMessageDialog(null,
                    TDSLanguageUtils.getMessage("cliente.error.conn") + "\n" + eMULRe.getMessage(),
                    TDSLanguageUtils.getMessage("cliente.error"), JOptionPane.ERROR_MESSAGE);
        } catch (Exception eE) {
            objRemotoMantenimiento = null;
            JOptionPane.showMessageDialog(null,
                    TDSLanguageUtils.getMessage("cliente.error.conn") + "\n" + eE.getMessage(),
                    TDSLanguageUtils.getMessage("cliente.error"), JOptionPane.ERROR_MESSAGE);
        }
    }

    /**
     * Permite buscar el identificador y el nombre de la ciudad
     * @return btnBuscar el botón Buscar
     */
    private JButton getBtnBuscar() {
        if (btnBuscar == null) {
            btnBuscar = new JButton();
            btnBuscar.setText(TDSLanguageUtils.getMessage("mantenimiento.gui.boton.buscar"));
            btnBuscar.addActionListener(new ActionListener() {

                public void actionPerformed(ActionEvent e) {
                    btnBuscarActionPerformed(e);
                }
            });
        }
        return btnBuscar;
    }

    /**
     * Permite confimar la acción del alta del usuario
     * @return El botón Aceptar
     */
    private JButton getBtnConfirmar() {
        if (btnConfirmar == null) {
            btnConfirmar = new JButton();
            btnConfirmar.setText(TDSLanguageUtils.getMessage("mantenimiento.gui.boton.aceptar"));
            btnConfirmar.addActionListener(new ActionListener() {

                public void actionPerformed(ActionEvent e) {

                    btnConfirmarActionPerformed(e);

                }
            });
        }
        return btnConfirmar;
    }

    /**
     * Realiza la acción asociada al botón Buscar
     * @param evt Evento que inicia la ejecución de la acción
     */
    private void btnBuscarActionPerformed(java.awt.event.ActionEvent evt) {
        Frame frame = JOptionPane.getFrameForComponent(this);
        DialogLocalidad dlgLocalidad = new DialogLocalidad(frame, true, usLogeado);
        dlgLocalidad.setVisible(true);
        CiudadDTO ciudadBuscada = dlgLocalidad.getCiudad();
        ciudad.setText(String.valueOf(ciudadBuscada.getIdCiudad()));
        nomCiudad.setText(ciudadBuscada.getNomCiudad());
    }

    /**
     *  Establece las acciones a realizar cuando cambia la selección de
     *  la casilla de verificación del rol Administrador
     */
    private void rolAdminItemStateChanged(java.awt.event.ItemEvent evt) {
        /* Rol Administrador seleccionado.  
         * Activa rol Tecnico y desactiva y deselecciona rol Cliente
         */
        if (rolAdmin.isSelected()) {
            rolCliente.setEnabled(false);
            rolCliente.setSelected(false);
            rolTecn.setEnabled(true);
            panelCC.setVisible(false);
        } else if (!rolTecn.isSelected()) {
            rolCliente.setEnabled(true);
            panelCC.setVisible(true);
        }
    }

    /**
     *  Establece las acciones a realizar cuando cambia la selección de
     *  la casilla de verificación del rol Técnico Auxiliar
     */
    private void rolTecnItemStateChanged(java.awt.event.ItemEvent evt) {
        /*  Activa rol Administrador y desactiva y deselecciona rol Cliente
         */
        if (rolTecn.isSelected()) {
            rolCliente.setEnabled(false);
            rolCliente.setSelected(false);
            rolAdmin.setEnabled(true);
            panelCC.setVisible(false);
        } else if (!rolAdmin.isSelected()) {
            rolCliente.setEnabled(true);
            panelCC.setVisible(true);
        }
    }

    /**
     *  Establece las acciones a realizar cuando cambia la selección de
     *  la casilla de verificación del rol Cliente
     */
    private void rolClienteItemStateChanged(java.awt.event.ItemEvent evt) {
        /* Rol Cliente seleccionado.  
         * Desactiva y deselecciona rol Administrador y rol Tecnico
         */
        if (rolCliente.isSelected()) {
            rolAdmin.setEnabled(false);
            rolAdmin.setSelected(false);
            rolTecn.setEnabled(false);
            rolTecn.setSelected(false);
            panelCC.setVisible(true);
        } else {
            rolAdmin.setEnabled(true);
            rolTecn.setEnabled(true);
            panelCC.setVisible(false);
        }
    }

    /**
     * Realiza la acción asociada al botón Cancelar
     * @param evt Evento que inicia la ejecución de la acción
     */
    private void btnCancelarActionPerformed(java.awt.event.ActionEvent evt) {
        dispose();
    }

    /**
     * Realiza el alta de un usuario en la base de datos
     * @param e evento del botón
     * @throws RemoteException
     * @throws GestorMantenimientoException 
     */
    private void btnConfirmarActionPerformed(java.awt.event.ActionEvent evt) {
        if (error) {
            JOptionPane.showMessageDialog(null, TDSLanguageUtils.getMessage("mantenimiento.usuario.alta.err.datos"));
        } else {
            if (ciudad.getText().equals("")) {
                JOptionPane.showMessageDialog(null, TDSLanguageUtils.getMessage("mantenimiento.usuario.alta.err.sinciudad"));
            } else {
                if (!(rolAdmin.isSelected() || rolTecn.isSelected() || rolCliente.isSelected())) {
                    JOptionPane.showMessageDialog(null, TDSLanguageUtils.getMessage("mantenimiento.usuario.alta.err.sinroles"));
                } else {
                    if (idUsuario.getText().equals("") || psw.getText().equals("") || nif.getText().equals("") || nombre.getText().equals("") || apellidos.getText().equals("")) {
                        JOptionPane.showMessageDialog(null, TDSLanguageUtils.getMessage("mantenimiento.usuario.alta.err.sindatos"));
                    } else {
                        if (!ValidarGUI.validaNifNie(nif.getText())) {
                            JOptionPane.showMessageDialog(null, TDSLanguageUtils.getMessage("mantenimiento.usuario.alta.err.nif"));
                        } else {

                            try {
                                AuditoriaDTO auditoria = new AuditoriaDTO();
                                UsuarioDTO usuario = new UsuarioDTO();

                                usuario.setIdUsuario(idUsuario.getText());
                                usuario.setNIF(nif.getText());
                                usuario.setPassword(psw.getText());
                                usuario.setNomUsuario(nombre.getText());
                                usuario.setApellidos(apellidos.getText());
                                usuario.setDomicilio(direccion.getText());
                                usuario.setIdCiudad(Integer.parseInt(ciudad.getText()));
                                usuario.setCodPostal(codPostal.getText());
                                usuario.setTelefono(telefono.getText());
                                usuario.setMovil(movil.getText());
                                usuario.setFax(fax.getText());
                                usuario.setEMail(email.getText());
                                usuario.setInactivo(Constantes.INACTIVO);

                                auditoria.setObjeto(Constantes.USUARIO);
                                auditoria.setSujeto(idConectado);
                                auditoria.setPk(usuario.getIdUsuario());
                                auditoria.setOperacion(Constantes.INSERCION);

                                objRemotoMantenimiento.altaUsuario(usuario);

                                if (rolTecn.isSelected()) {
                                    objRemotoMantenimiento.usuarioRol(idUsuario.getText(), Constantes.ROL_TECNICO);
                                }

                                if (rolCliente.isSelected()) {
                                    objRemotoMantenimiento.usuarioRol(idUsuario.getText(), Constantes.ROL_CLIENTE);
                                    objRemotoMantenimiento.ccCliente(cc.getText(), idUsuario.getText());
                                }

                                if (rolAdmin.isSelected()) {
                                    objRemotoMantenimiento.usuarioRol(idUsuario.getText(), Constantes.ROL_ADMINISTRADOR);
                                }

                                objRemotoMantenimiento.altaAuditoria(auditoria);

                                JOptionPane.showMessageDialog(null, TDSLanguageUtils.getMessage("mantenimiento.usuario.alta.correcta"));

                                // Inicialización de los campos de texto del formulario
                                inicializaControles();

                            } catch (GestorMantenimientoException gmE) {
                                JOptionPane.showMessageDialog(null,
                                        gmE.getMessage(), TDSLanguageUtils.getMessage("gmantenimiento.err.usuario.alta"),
                                        JOptionPane.ERROR_MESSAGE);
                            } catch (RemoteException rE) {
                                JOptionPane.showMessageDialog(null,
                                        rE.getMessage(), TDSLanguageUtils.getMessage("gmantenimiento.err.usuario.alta"),
                                        JOptionPane.ERROR_MESSAGE);
                            }
                        }
                    }
                }
            }
        }
    }

    /**
     * Establece los valores iniciales de los controles del formulario
     */
    private void inicializaControles() {

        idUsuario.setText(TDSLanguageUtils.getMessage("mantenimiento.gui.campostexto.sintexto"));
        nif.setText(TDSLanguageUtils.getMessage("mantenimiento.gui.campostexto.sintexto"));
        nombre.setText(TDSLanguageUtils.getMessage("mantenimiento.gui.campostexto.sintexto"));
        apellidos.setText(TDSLanguageUtils.getMessage("mantenimiento.gui.campostexto.sintexto"));
        psw.setText(TDSLanguageUtils.getMessage("mantenimiento.gui.campostexto.sintexto"));
        direccion.setText(TDSLanguageUtils.getMessage("mantenimiento.gui.campostexto.sintexto"));
        codPostal.setText(TDSLanguageUtils.getMessage("mantenimiento.gui.campostexto.sintexto"));
        ciudad.setText(TDSLanguageUtils.getMessage("mantenimiento.gui.campostexto.sintexto"));
        nomCiudad.setText(TDSLanguageUtils.getMessage("mantenimiento.gui.campostexto.sintexto"));
        telefono.setText(TDSLanguageUtils.getMessage("mantenimiento.gui.campostexto.sintexto"));
        movil.setText(TDSLanguageUtils.getMessage("mantenimiento.gui.campostexto.sintexto"));
        fax.setText(TDSLanguageUtils.getMessage("mantenimiento.gui.campostexto.sintexto"));
        email.setText(TDSLanguageUtils.getMessage("mantenimiento.gui.campostexto.sintexto"));
        cc.setText(TDSLanguageUtils.getMessage("mantenimiento.gui.campostexto.sintexto"));
        cc.setVisible(false);

        inactivo.setSelected(true);

        rolAdmin.setSelected(false);
        rolTecn.setSelected(false);
        rolCliente.setSelected(false);
    }
}
